<template>
  <el-dialog
    v-model="isModel"
    :title="`${modelId ? '编辑模型' : '添加模型'}`"
    width="600px"
    :append-to-body="!isModel"
    :before-close="cancel"
  >
    <el-form
      v-loading="loading"
      ref="ruleFormRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
    >
      <!-- 11 -->
      <el-form-item label="模型名称" prop="name">
        <el-input
          v-model="formData.name"
          placeholder="请输入模型名称"
          clearable
          maxlength="20"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        v-for="(item, index) in formData.journeyStrategyEntityList"
        :key="index"
        :label="`策略${index + 1}`"
        :prop="`journeyStrategyEntityList.${index}.name`"
        :rules="[
          {
            required: true,
            message: '请输入策略',
            trigger: 'blur',
          },
        ]"
      >
        <!-- <el-input v-model="domain.value" /> -->
        <div style="display: flex; align-item: center">
          <el-input
            v-model="item.name"
            clearable
            maxlength="20"
            show-word-limit
            placeholder="请输入策略名称"
          />

          <div class="button-box">
            <el-button
              type="text"
              @click="moveUp(index)"
              size="small"
              :disabled="index == 0"
              >上移</el-button
            >
            <el-button
              type="text"
              @click="moveDown(index)"
              :disabled="formData.journeyStrategyEntityList.length == index + 1"
              size="small"
              >下移</el-button
            >
            <el-button
              @click="addStrategy(index)"
              size="small"
              icon="Plus"
              circle
            />
            <el-button
              v-if="formData.journeyStrategyEntityList.length > 1"
              @click="delStrategy(index)"
              size="small"
              icon="Delete"
              circle
            />
          </div>
        </div>
      </el-form-item>

      <el-form-item label="状态">
        <el-switch
          v-model="formData.status"
          :active-value="1"
          :inactive-value="0"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)"
          >确定</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import MarketingModelApi from "@/api/marketingModelApi.js";
import type { FormInstance } from "element-plus";
import { reactive, ref } from "vue";
import { ElMessage } from "element-plus";
const props = defineProps({
  isModel: Boolean,
  modelId: Number,
  modelData: {
    type: Object,
    default: {},
  },
});
const emit = defineEmits(["confirmFormData", "cancel"]);
const { isModel, modelId, modelData } = toRefs(props);
const loading = ref(false);
const ruleFormRef = ref<FormInstance>();
// const formData = ref<{
//   id: number;
//   name: string;
//   status: number;
//   journeyStrategyEntityList: DomainItem[];
// }>({
//   journeyStrategyEntityList: [
//     {
//       name: "",
//     },
//   ],
//   name: "",
//   status: 0,
//   id: Number(),
// });
const formData = ref({
  journeyStrategyEntityList: [
    {
      name: "",
      orderNum: Number(),
    },
  ],
  name: "",
  status: 0,
  id: Number(),
});

interface DomainItem {
  name: string;
}
const rules = ref({
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
});

watch(
  () => modelId?.value,
  () => {
    if (modelId?.value) {
      console.log("watch-modelData", modelData);
      if (modelId?.value) {
        getMarketingModelDetail();
      }
    }
  }
);

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid, fields) => {
    if (valid) {
      addMarketingModel();
    } else {
      console.log("error submit!", fields);
    }
  });
};

const addMarketingModel = async () => {
  if (modelId) {
    formData.value.id = Number(modelId.value);
  }
  // 添加排序字段
  formData.value.journeyStrategyEntityList.forEach((item, index) => {
    item.orderNum = index + 1;
  });
  let rs = await MarketingModelApi.addMarketingModel(formData.value);
  if (rs.code === 200) {
    ElMessage({
      showClose: true,
      message: "添加模块成功",
      type: "success",
    });
    confirmFormData();
  }
};

// 详情
const getMarketingModelDetail = async () => {
  loading.value = true;
  let rs = await MarketingModelApi.getMarketingModelDetail({
    id: modelId?.value,
  });
  if (rs.code === 200) {
    console.log(formData);
    formData.value = rs.payload;
    console.log("formData.value", formData.value);
    console.log("rs.payload", rs.payload);
  }
  loading.value = false;
};
// 位置调换
const swapItems = (arr: any, index1: any, index2: any) => {
  arr[index1] = arr.splice(index2, 1, arr[index1])[0];
  return arr;
};

// 上移
const moveUp = (index: any) => {
  formData.value.journeyStrategyEntityList = swapItems(
    formData.value.journeyStrategyEntityList,
    index,
    index - 1
  );
};
// 下移
const moveDown = (index: any) => {
  formData.value.journeyStrategyEntityList = swapItems(
    formData.value.journeyStrategyEntityList,
    index,
    index + 1
  );
};

const addStrategy = (index: any) => {
  if(formData.value.journeyStrategyEntityList.length >= 9) {
    ElMessage({
      showClose: true,
      message: "最多可以添加九条策略",
      type: "warning",
    });
    return
  }
  formData.value.journeyStrategyEntityList.splice(index + 1, 0, {
    name: "",
    orderNum: Number(),
  });
};
const delStrategy = (index: any) => {
  formData.value.journeyStrategyEntityList.splice(index, 1);
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) {
    return;
  }
  formEl.resetFields();
};

const cancel = () => {
  emit("cancel");
  formData.value = {
    journeyStrategyEntityList: [
      {
        name: "",
        orderNum: Number(),
      },
    ],
    name: "",
    status: 0,
    id: Number(),
  };
  resetForm(ruleFormRef.value);
};
const confirmFormData = () => {
  emit("confirmFormData");
  cancel()
};
onMounted(() => {
  // console.log("modelData", props.modelData);
});
</script>

<style lang="scss" scoped>
.el-input {
  width: 300px;
}
.button-box {
  widows: 100px;
  display: flex;
  align-items: center;
  margin-left: 10px;
  .el-button {
    width: 20px;
    height: 20px;
  }
}
</style>
